python SyntaxError Non-ASCII character \xe9 in file xxx

错误类型:SyntaxError: Non-ASCII character \xe9 in file xxx

最近写 python 代码的时候,简单的一下代码,确出现错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
points = int(raw_input("领先的分数:"))
is_in_control = raw_input("是否领先队控球(Y/N:)")
last_seconds = int(raw_input("比赛剩余秒数:"))
points -= 3
if is_in_control == 'Y':
points += 0.5
else:
points -= 0.5
if points < 0:
points = 0
points = points ** 2
if points > last_seconds:
print "safe"
else:
print "unsafe"
1
SyntaxError: Non-ASCII character '\xe9' in file /Users/programersunny/PycharmProjects/pythonDemo/hello on line 58, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

打开 URL 阅读了一下,找到原因:

Python will default to ASCII as standard encoding if no other encoding hints are given.

Python的默认编码文件是用的ASCII码,你将文件存成了UTF-8也没用。

解决办法很简单:

只要在文件开头加入# -*- coding: UTF-8 —或者#coding=utf-8 就行了。

注意,这两行代码必须添加在.py文件的第一行或者第二行。如果在第三行以及以上,都没有效果,这个在这个网址上也有描述

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file

翻译一下:

为了定义源码的编码格式,一个神奇的注释需要被添加到源文件的第一行或者第二行中。

神奇的注释已经在上文提到了。

上文提到的URL地址

纪念一下自己在 python 中遇到的第一个小坑。

CepheusSun wechat
订阅我的公众号,每次更新我都不一定会告诉你!
坚持原创技术分享,您的支持将鼓励我继续创作!
0%